import { Encrypt } from "@/utils/crypto.js";
import CryptoJS from "crypto-js";
import { Toast } from "vant";

export function getUrlParams(key) {
  const params = new URLSearchParams(window.location.search);
  if (key) {
    return params.get(key);
  } else {
    const result = {};
    for (const [paramKey, paramValue] of params.entries()) {
      result[paramKey] = paramValue;
    }
    return result;
  }
}
export function loadScript(url) {
  return new Promise((resolve, reject) => {
    // 创建一个新的 script 元素
    const script = document.createElement("script");

    // 设置 script 的 src 属性为要加载的 JS 文件的 URL
    script.src = url;

    // 设置 script 的 type 属性为 'text/javascript'
    script.type = "text/javascript";

    // 可选：设置 script 的 async 或 defer 属性
    // script.async = true; // 异步加载，不保证执行顺序
    // script.defer = true; // 延迟加载，保证执行顺序

    // 添加 script 元素到文档的 head 中
    document.head.appendChild(script);

    // 添加 onload 事件处理程序，以便在脚本加载完成后解析 Promise
    script.onload = function () {
      console.log(`Script loaded: ${url}`);
      resolve();
    };

    // 添加 onerror 事件处理程序，以便在脚本加载失败时拒绝 Promise
    script.onerror = function () {
      console.error(`Failed to load script: ${url}`);
      reject(new Error(`Failed to load script: ${url}`));
    };
  });
}
//资讯相关逻辑要不域名替换成https://wservice.iwencai.com/test
//比如 https://news.10jqka.com.cn/q664512076/ =》》》》https://wservice.iwencai.com/test/news/q664512076/
export function replaceWservice(url) {
  if (url.indexOf("https://news.10jqka.com.cn/") > -1) {
    // 4.替换资讯地址，统一走https://wservice.iwencai.com/test/news/地址（资讯纯净页）
    url = url.replace(
      "https://news.10jqka.com.cn/",
      "https://wservice.iwencai.com/test/news/"
    );
  } else if (url.indexOf("yikeapp") > -1) {
    // 5.解决百科跳转wservice问题（百科地址不含有vaprotocol）
    const params = urlArr[1];
    const host = "https://wservice.iwencai.com/test/yikeapp/";
    const newUrl = `${host}?${params}`;
    url = newUrl;
  }
  return url;
}

/**
 * 随机生成用户id
 */
export function generateUserId() {
  // 高精度时间戳 (13位) + 随机数 (19位)
  const timestamp = Date.now().toString(16).padStart(12, "0");
  const randomPart = Array.from(crypto.getRandomValues(new Uint8Array(10)))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("")
    .slice(0, 20);

  return timestamp + randomPart;
}

/**
 * 加密
 * @returns
 */
let USER_ID = "USER_ID";
export function _getRandomUserId() {
  let userId = localStorage.getItem(USER_ID);
  if (!userId) {
    userId = generateUserId();
    userId = Encrypt(userId);
    localStorage.setItem(USER_ID, userId);
  }
  return userId;
}

/**
 *
 * @returns {string} 返回设备类型
 */
export function detectDeviceType() {
  const ua = navigator.userAgent.toLowerCase();
  if (/iphone|ipad|ipod/.test(ua)) {
    return "iphone";
  } else if (/android/.test(ua)) {
    return "android";
  } else {
    return "web";
  }
}
/**
 * 生成sessionCode(uuid)
 * @param {number} len 长度 32
 * @param {number} radix 进制 16
 */

export function _getSessionCode(len, radix) {
  let chars =
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  let uuid = [],
    i;
  radix = radix || chars.length;
  if (len) {
    for (i = 0; i < len; i++) {
      uuid[i] = chars[0 | (Math.random() * radix)];
    }
  } else {
    let r;
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
    uuid[14] = "4";
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16);
        uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r];
      }
    }
  }
  return uuid.join("");
}

/**
 * 获取session_id
 * @param {*} user_id
 * @param {*} source
 * @returns
 */
export function _getSessionId(user_id, source) {
  return CryptoJS.MD5(user_id + source + Date.now()).toString();
}

/**
 * 获取user_name
 * @param {*} length
 * @param {*} charArr
 * @returns
 */
export function getRandomStr(length, charArr) {
  let str = "",
    backArr = [],
    arr = "abcdefghijklmnopqrstuvwxyz0123456789".split(""),
    i,
    len,
    num;
  length = typeof length === "number" && length > 0 ? parseInt(length) : 0; // charArr参数合法时将其用作候选字符集合
  if (charArr instanceof Array && charArr.length > 0) {
    arr = charArr;
  }
  len = arr.length; // 按照目标长度，逐一生成随机字符
  for (i = 0; i < length; i++) {
    num = Math.floor(Math.random() * len);
    backArr.push(arr[num]);
  }
  str = backArr.join("");
  return str;
}

export function s4() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
/**
 * 获取reqid
 * @returns
 */
export function getReqid() {
  return (
    s4() +
    s4() +
    "-" +
    s4() +
    "-" +
    s4() +
    "-" +
    s4() +
    "-" +
    s4() +
    s4() +
    s4()
  );
}






export async function copyText(textToCopy) {
  const res = await fallbackCopyText(textToCopy);
  if (res) {
    Toast("复制成功!");
  } else {
    Toast("复制失败!");
  }
  function fallbackCopyText(text) {
    return new Promise((resolve, reject) => {
      const textarea = document.createElement("textarea");
      textarea.value = text;
      textarea.style.position = "fixed"; // 防止滚动
      document.body.appendChild(textarea);
      textarea.select();

      try {
        const successful = document.execCommand("copy");
        if (successful) {
          resolve(true);
        } else {
          reject(false);
        }
      } catch (err) {
        console.error("备用方法复制失败:", err);
        console.log("手动复制：Ctrl+C 或 Command+C");
      } finally {
        document.body.removeChild(textarea);
      }
    });
  }
}
